package ren.colorful.thread;

import java.util.HashMap;

import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;


/**
 * 读写锁：写锁具有排他性，读锁具有共享性，写锁没有解锁之前，所有的其他线程阻塞
 * @author fulin
 *
 */

public class ReadWriteThread {
    private volatile Map<String,String> cache = new HashMap<String,String>();

    private ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();

    public void add(String key,String val){
        ReentrantReadWriteLock.WriteLock writeLock = null;
        try{
            writeLock = rwLock.writeLock();
            writeLock.lock();
            cache.put(key,val);
            System.out.println("数据已经写入缓存");
            TimeUnit.SECONDS.sleep(10L);
        }catch (Exception e){
            System.out.printf("e");
        }finally {
            if(writeLock != null){
                writeLock.unlock();
            }
        }
    }

    public void get(String key){
    	ReentrantReadWriteLock.ReadLock readLock = null;
    	try {
			readLock = rwLock.readLock();
			readLock.lock();
			String val = cache.get(key);
			System.out.println("读到的值是"+val);
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			if(readLock != null) {
				readLock.unlock();
			}
		}
    }
    
    public static void main(String[] args) throws InterruptedException {
    	final ReadWriteThread th = new ReadWriteThread();
    	new Thread(()->{
    		th.add("1", "ok");
    	}).start();
    	
    	new Thread(() -> {
    		th.get("1");
    	}).start();
    	
    	
//    	TimeUnit.SECONDS.sleep(5L);
    	
	}
}
